<template>
  <router-view />
</template>

<script setup>
import { onMounted, onUnmounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useQuasar, Loading, QSpinnerIos } from "quasar";
import { handleLoginStatus, checkStatusTimer, LoadingBar } from "src/js/common";

const route = useRoute();
const $q = useQuasar();
const router = useRouter();

// 处理登录数据的函数
const handleLoginData = async () => {
  console.log("Route query:", route.query);
  console.log("Current URL:", location.href);
  console.log("Location hash:", location.hash);
  console.log("Location search:", location.search);

  // 尝试从route.query中获取LoginData
  if (route.query?.LoginData) {
    const loginDataBase64 = decodeURIComponent(route.query.LoginData);
    const LoginDataJSON = atob(loginDataBase64);
    const loginData = JSON.parse(LoginDataJSON);
    Object.entries(loginData).forEach(([key, value]) => {
      localStorage.setItem(key, value);
    });
    // remove LoginData from query
    await router.replace({
      query: {},
    });
    location.href =
      location.origin + "/#/" + (location.href.split("/#/")[1] || "");
    return true;
  }

  // 尝试从location.search中获取LoginData（兼容性处理）
  if (location.search.includes("LoginData")) {
    // get params from query
    const params = new URLSearchParams(location.search);
    const LoginDataBase64 = params.get("LoginData");
    const LoginDataJSON = atob(LoginDataBase64);
    const loginData = JSON.parse(LoginDataJSON);
    Object.entries(loginData).forEach(([key, value]) => {
      localStorage.setItem(key, value);
    });
    // remove the url query
    location.search = "";
    location.href =
      location.origin + "/#/" + (location.href.split("/#/")[1] || "");
    return true;
  }

  // 处理hash中的查询参数（针对 /#/?id=1 这种格式）
  if (location.hash.includes("?")) {
    const hashPart = location.hash.split("?")[1];
    const params = new URLSearchParams(hashPart);
    const hashQuery = Object.fromEntries(params);
    console.log("Hash query:", hashQuery);

    if (hashQuery.LoginData) {
      const loginDataBase64 = decodeURIComponent(hashQuery.LoginData);
      const LoginDataJSON = atob(loginDataBase64);
      const loginData = JSON.parse(LoginDataJSON);
      Object.entries(loginData).forEach(([key, value]) => {
        localStorage.setItem(key, value);
      });
      // 清理URL
      location.href = location.origin + "/#/";
      return true;
    }
  }

  return false;
};

onMounted(async () => {
  Loading.setDefaults({
    spinner: QSpinnerIos,
    spinnerSize: 40,
    spinnerColor: "grey-8",
    backgroundColor: "grey-3",
  });
  LoadingBar.setDefaults({ color: "primary" });

  // 立即尝试处理登录数据
  const hasLoginData = await handleLoginData();

  // 如果没有登录数据，检查登录状态
  if (
    !hasLoginData &&
    localStorage.getItem("token") &&
    localStorage.getItem("email")
  ) {
    $q.loading.show();
    await handleLoginStatus();
    $q.loading.hide();
  }
});

// 监听路由变化
watch(
  () => route.query,
  async (newQuery) => {
    console.log("Route query changed:", newQuery);
    await handleLoginData();
  },
  { immediate: true }
);

onUnmounted(() => {
  if (checkStatusTimer.value) {
    clearInterval(checkStatusTimer.value);
    checkStatusTimer.value = null;
  }
});
</script>
